package com.xf.zk.curator.example.znode;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class SetData {
	public static void main(String[] args) throws Exception {
		String path = "/curator-create-setData/c1";
		// 创建CuratorFramework 客户端实例，集群服务器地址为127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183，session timeout5000ms
		// 回调策略为ExponentialBackoffRetry，即为retries 3 times with increasing 1000 sleep time between retries
		CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
				.sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
		// 开始连接
		client.start();
		// 创建 EPHEMERAL类型节点，并创建父节点
		client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());
		Stat stat = new Stat();
		// 获取节点数据，存储stat在new Stat()中，路径为/curator-create-setData/c1
		client.getData().storingStatIn(stat).forPath(path);
		// 设置数据，版本号为获取数据的版本号，路径为/curator-create-setData/c1
		Stat stat1 = client.setData().withVersion(stat.getVersion()).forPath(path);
		System.out.println("Success set node for : " + path + ", new version: "
				+ stat1.getVersion());
		try {
			// 重新设置数据，版本号为获取数据的版本号，路径为/curator-create-setData/c1
			client.setData().withVersion(stat.getVersion()).forPath(path);
		} catch (Exception e) {
			// 版本不一致报错
			System.out.println("Fail set node due to " + e.getMessage());
		}
	}
}
